<?php

namespace haibao\jiepai\business;

use haibao\app\business\ImageLibrary;
use haibao\frame\data\query\Condition;
use \haibao\jiepai\data\User as UserData;
use \haibao\jiepai\model\data\user\CmsUsers as CmsUsersModel;
use \haibao\classlibrary\jiepai\Config as CConfig;

class User extends Base
{

    /**
     * 用户管理信息
     */
    const TYPE_MANAGE_ALL = 'all';
    const TYPE_MANAGE_CANSOLVE = 'canSolve';
    const TYPE_MANAGE_SILENCE = 'silence';
    const TYPE_MANAGE_FREEZE = 'freeze';

    public static $userStatus = array(
        self::TYPE_MANAGE_ALL => '全部',
        self::TYPE_MANAGE_CANSOLVE => '可处理',
        self::TYPE_MANAGE_SILENCE => '禁言中',
        self::TYPE_MANAGE_FREEZE => '已封号',
    );

    public static $userInfoStatus = array(
        CmsUsersModel::STATUS_NORMAL => '正常',
        CmsUsersModel::STATUS_BAN => '禁言',
        CmsUsersModel::STATUS_CLOSE => '封号'
    );

    /*
     * 异常类型
     */
    const TYPE_UNTYPE_1 = 'UnPassTypeNum1';//评论涉嫌广告数
    const TYPE_UNTYPE_2 = 'UnPassTypeNum2';//评论言论不实数
    const TYPE_UNTYPE_3 = 'UnPassTypeNum3';//评论言论过激数
    const TYPE_UNTYPE_4 = 'UnPassTypeNum4';//评论纠纷举报数
    const TYPE_UNTYPE_5 = 'UnPassTypeNum5';//评论网监违禁数
    const TYPE_UNTYPE_6 = 'UnPassTypeNum6';//其他
    const TYPE_PUNISH_1 = 'PunishTypeNum1';//禁言警告
    const TYPE_PUNISH_2 = 'PunishTypeNum2';//封号警告

    public static $exceptionType = array(
        self::TYPE_UNTYPE_1 => '评论-涉嫌广告',
        self::TYPE_UNTYPE_2 => '评论-言论不实',
        self::TYPE_UNTYPE_3 => '评论-言论过激',
        self::TYPE_UNTYPE_4 => '评论-纠纷举报',
        self::TYPE_UNTYPE_5 => '评论-网监违禁',
        self::TYPE_UNTYPE_6 => '评论-其他',
        self::TYPE_PUNISH_1 => '禁言警告',
        self::TYPE_PUNISH_2 => '封号警告',
    );

    /**
     *
     * 获取所有用户
     */
    public static function getUsersByFilter($filter)
    {
        $data = new UserData();
        return $data->getAll($filter);
    }

    /**
     *
     * 获取一个用户
     */
    public static function getOneByFilter($filter)
    {
        $data = new UserData();
        return $data->getOne($filter);
    }

    public static function insertUserTitle($userId, $userTitle = 0)
    {
        if (!$userId) {
            throw new BusinessException('用户id不能为空');
        }
        $data = new UserData();
        return $data->insertUserTitle($userId, $userTitle);
    }

    public static function userLogin($userModel)
    {
        $data = new UserData();
        return $data->userLogin($userModel);
    }

    public static function userLogout($userId)
    {
        $data = new UserData();
        $data->userLogout($userId);
    }

    public static function saveAvatar($userId, $stream, $uploadFile)
    {
        $ext = self::getImageExt($stream);
        $orgPath = self::getAbsolutePath($uploadFile . self::getAvatarById($userId, 'big'));
        self::createDir($orgPath);
        file_put_contents($orgPath, $stream);

        $sizeArr = array(
            'small' => '48*48',
            'middle' => '120*120',
            'big' => '200*200'
        );
        foreach ($sizeArr as $type => $size) {
            $path = $uploadFile . self::getAvatarById($userId, $type);
            $typePath = self::getAbsolutePath($path);
            list($width, $height) = explode('*', $size);
            self::createDir($typePath);
            self::imagecropper($orgPath, $typePath, $width, $height);
        }
    }

    public static function CheckUserStatus($userId)
    {
        $data = new UserData();
        return $data->CheckUserStatus($userId);
    }

    public static function updateUser($userId, $arrSet)
    {
        $data = new UserData();
        $data->updateUser($userId, $arrSet);
    }

    /**
     * 保存manage
     */
    public static function saveManageUser($option)
    {
        $data = new UserData();

        if (in_array(\haibao\cms\business\base::getCurrentUser()->Id, array_keys(\haibao\jiepai\business\Base::$userMap))) {
            $option['auditUser'] = \haibao\jiepai\business\Base::$userMap[\haibao\cms\business\base::getCurrentUser()->Id]['id'];
        } else {
            $option['auditUser'] = 5;
        }
        return $data->saveManageUser($option);
    }

    /**
     * 根据Model保存
     */
    public static function saveByModel($model)
    {
        $data = new UserData();
        return $data->add($model);
    }

    /**
     * 获取所有用户信息
     */
    public static function getUserList($option)
    {
        $data = new UserData();
        return $data->getUserList($option);
    }

    /**
     *
     * 获取所有用户管理数据
     */
    public static function getUserManageList($option)
    {
        $data = new UserData();
        return $data->getUserManageList($option);
    }

    public static function getExaminedReports($option = array())
    {

        $data = new UserData();
        return $data->getExaminedReports($option);
    }

    public static function getReportContextUsers($commentId, $commentType)
    {

        $data = new UserData();
        return $data->getReportContextUsers($commentId, $commentType);
    }

    public static function getUserFeedbacks($option)
    {
        $data = new UserData();
        return $data->getUserFeedbacks($option);

    }

    public static function getFeedbackPictures($typeId, $type)
    {
        $data = new UserData();
        return $data->getFeedbackPictures($typeId, $type);

    }

    public static function getAdviceList($userId, $adviceId)
    {
        $data = new UserData();
        return $data->getAdviceList($userId, $adviceId);
    }

    /**
     * @param \haibao\jiepai\model\data\advice\CmsAdvice $model
     * @param array $picIds
     * @return adviceId
     */
    public static function addAdvice($model, $picIds)
    {
        $data = new UserData();
        return $data->addAdvice($model, $picIds);
    }

    /**
     * @param \haibao\jiepai\model\data\user\CmsAdviceReply $model
     * @param array $picIds
     * @return replayId
     */
    public static function addUserAdviceReply($model, $picIds)
    {
        $data = new UserData();
        return $data->addUserAdviceReply($model, $picIds);
    }

    public static function fixAdvice($adviceId, $userId)
    {
        $data = new UserData();
        return $data->fixAdvice($adviceId, $userId);
    }

    public static function addAdviceReply($optionData)
    {
        $data = new UserData();
        return $data->addAdviceReply($optionData);
    }

    public static function getFeedback($adviceId)
    {

        if (!$adviceId) {
            throw new BusinessException('反馈id不能为空');
        }
        $data = new UserData();
        return $data->getFeedback($adviceId);
    }

    public static function getFeedbackReply($adviceId)
    {

        if (!$adviceId) {
            throw new BusinessException('反馈id不能为空');
        }
        $data = new UserData();
        return $data->getFeedbackReply($adviceId);
    }

    public static function updateAdviceStatus($adviceId, $status = \haibao\jiepai\model\data\advice\CmsAdvice::STATUS_YES)
    {

        $data = new UserData();
        $data->updateAdviceStatus($adviceId, $status);
    }

    public static function getHaibaoUserList($haibaoUserFilter)
    {
        if (!$haibaoUserFilter) {
            throw new BusinessException('error');
        }
        $haibaoUserData = new \haibao\jiepai\data\CmsHaibaoEditors();
        return $haibaoUserData->getAll($haibaoUserFilter);
    }

    public static function closeAdviceReply($replyId)
    {
        if (!$replyId) {
            throw new BusinessException('回复id不能为空');
        }

        $data = new UserData();
        $data->closeAdviceReply($replyId);
    }

    public static function getVestUserList($cmsAdminUser)
    {
        if (!$cmsAdminUser) {
            throw new BusinessException('error');
        }
        $cmsAdminUsersData = new \haibao\jiepai\data\CmsAdminUsers();
        return $cmsAdminUsersData->getAll($cmsAdminUser);
    }

    /**
     * 通过Sid获取UserID
     * @param $sid
     */
    public static function getUserInfo($sid)
    {
        $data = new UserData();
        return $data->getUserInfo($sid);
    }

    /**
     *  1->文章点赞，2->文章收藏，3->评论点赞，4->关注达人,5->回复点赞
     * @param unknown $type
     * @param unknown $articleIds
     * @param unknown $UserID
     * @return multitype:NULL
     */
    public static function getUserActions($type, $articleIds, $userId)
    {
        $data = new UserData();
        return $data->getUserActions($type, $articleIds, $userId);
    }

    public static function insertUserActions($type, $articleIds, $userId)
    {
        $data = new UserData();
        return $data->insertUserActions($type, $articleIds, $userId);
    }

    public static function updateUserActions($flag, $type, $articleIds, $userId)
    {
        $data = new UserData();
        return $data->updateUserActions($flag, $type, $articleIds, $userId);
    }

    public static function cancelCollectArticles($type, $articleIds, $userId)
    {
        $data = new UserData();
        return $data->cancelCollectArticles($type, $articleIds, $userId);
    }

    public static function replaceVisitorToUser($deviceId, $userId)
    {
        $data = new UserData();
        $data->replaceVisitorToUser($deviceId, $userId);
    }

    public static function isEditorUser($userId)
    {
        $data = new \haibao\jiepai\data\CmsAdminUsers();
        return $data->isEditorUser($userId);
    }

    public static function getFashionistaList($filter)
    {
        $data = new UserData();
        return $data->getAll($filter);
    }

    public static function getUserSubscribeOldDate($userId)
    {
        $data = new UserData();
        return $data->getUserSubscribeOldDate($userId);
    }

    public static function checkSubscribeTagHaveNew($tagId, $lastDataTime = null, $isCelebrity = false)
    {
        $data = new UserData();
        return $data->checkSubscribeTagHaveNew($tagId, $lastDataTime, $isCelebrity);
    }

    public static function setUserSubscribeDate($userId)
    {
        $cache = new \haibao\jiepai\cache\User();
        $newDate = $cache->getUserSubscribeNewDate($userId);
        if (empty($newDate)) {
            $cache->setUserSubscribeNewDate($userId, date('Y-m-d H:i:s', time()));
        } else {
            //判断是否同一天，不是则更新缓存
            if (date('Ymd', strtotime($newDate)) != date('Ymd')) {
                $cache->setUserSubscribeNewDate($userId, date('Y-m-d H:i:s', time()));
            }
        }
    }


    /**
     * 根据二进制流判断图片格式
     */
    private static function getImageExt($stream)
    {
        $jfif_exif = substr($stream, 0, 100);
        if (strpos($jfif_exif, 'JFIF') || strpos($jfif_exif, 'JPEG') || strpos($jfif_exif, 'JPG') || strpos($jfif_exif, 'Exif') || strpos($jfif_exif, 'EXIF')) {
            $ext = '.jpg';
        } else if (strpos($jfif_exif, 'PNG')) {
            $ext = '.png';
        } else if (strpos($jfif_exif, 'GIF')) {
            $ext = '.gif';
        } else {
            $ext = '.jpg';
        }
        return $ext;
    }

    /**
     * 获取保存图片的绝对路径
     */
    private static function getAbsolutePath($path)
    {
        return rtrim(\haibao\classlibrary\Config::getConfig(\haibao\classlibrary\Config::STORAGE_PATH_UPLOADS), 'cms_img_uploads/') . '/uc_server/data' . $path;
    }

    /**
     * 创建文件保存路径
     */
    private static function createDir($path)
    {
        $path = pathinfo($path);
        return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
    }

    /**
     * 根据用户id获取用户真实头像地址
     */
    public static function getAvatarById($userId, $size = 'middle', $type = '')
    {
        $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'big';
        $userId = abs(intval($userId));
        $userId = sprintf("%09d", $userId);
        $dir1 = substr($userId, 0, 3);
        $dir2 = substr($userId, 3, 2);
        $dir3 = substr($userId, 5, 2);
        $typeadd = $type == 'real' ? '_real' : '';
        return $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($userId, -2) . $typeadd . "_avatar_$size.jpg";
    }

    public static function getUserSubscribeOptions($userId)
    {
        $data = new UserData();
        return $data->getUserSubscribeOptions($userId);
    }

    public static function getUserSubscribes($tagIds, $columnsId = array(), $celebrityIds = array(), $lastTime = 0, $limit = 30, $userId = 0)
    {
        $data = new UserData();

        $result = $data->getUserSubscribes($tagIds, $columnsId, $celebrityIds, $lastTime, $limit);
        if ($result) {
            $pictureIds = array();
            foreach ($result as $key => &$picture) {
                $picture['FileID'] = intval($picture['FileID']);
                array_push($pictureIds, $picture['FileID']);
            }

            // 查询用户是否收藏图片和点赞数量
            $collectResult = \haibao\jiepai\business\Picture::getIsCollect($userId, $pictureIds);
            $praiseResult = \haibao\jiepai\business\Picture::getIsPraise($userId, $pictureIds);

            // 查询图片评论数量
            $commentResult = \haibao\jiepai\business\Comment::getCommentCountByImageIds($pictureIds);

            // 查询图片收藏来源文章
            $sourceResult = \haibao\jiepai\business\Picture::getCollectSource($pictureIds);

            //SourceType （收藏来源类型 1文章或私照2） SourceTypeID （文章ID或人物ID）
            $sourceIdResult = \haibao\jiepai\business\Picture::getCollectSourceById($pictureIds);
            foreach ($result as $key => &$picture) {
                $picture['Tags'] = intval($picture['Tags']);
                $picture['IsPictureCollect'] = isset($collectResult[$picture['FileID']]) ? $collectResult[$picture['FileID']] : 0;
                $picture['IsPicturePraise'] = isset($praiseResult[$picture['FileID']]) ? $praiseResult[$picture['FileID']] : 0;
                $picture['CommentCount'] = isset($commentResult[$picture['FileID']]) ? $commentResult[$picture['FileID']] : 0;
                $picture['CollectSource'] = isset($sourceResult[$picture['FileID']]) ? $sourceResult[$picture['FileID']] : '';
                if (empty($picture['CollectSource'])) {
                    $picture['CollectSource'] = $picture['Title'];
                }
                $picture['SourceType'] = isset($sourceIdResult[$picture['FileID']]) ? $sourceIdResult[$picture['FileID']]['SourceType'] : 0;
                $picture['SourceTypeID'] = isset($sourceIdResult[$picture['FileID']]) ? $sourceIdResult[$picture['FileID']]['SourceTypeID'] : 0;
                if ($picture['SourceType'] == 4 || $picture['SourceType'] == 0) {
                    $picture['SourceType'] = 7;
                    $picture['SourceTypeID'] = intval($picture['Tags']);
                }


            }
        }

        return $result;
    }

    public static function getColumnsList($columnsIds)
    {
        if (empty($columnsIds)) {
            return array();
        }
        $data = new UserData();
        return $data->getColumnsList($columnsIds);
    }

    /**
     * 检查重名
     */
    public static function checkSubscribeHaveNew($userId)
    {
        $data = new UserData();
        $userCache = new \haibao\jiepai\cache\User();
        $userDataCache = $userCache->getUserSubscribeNewDate($userId);
        $option = $data->getUserSubscribeOptions($userId);
        $result = $data->checkSubscribeHaveNew($option, $userDataCache);
        return $result;
    }

    /**
     * 获取nickName
     */
    public static function getNickNameByUserIds($userIds)
    {
        $userNickNames = array();
        if (!$userIds) {
            return $userNickNames;
        }
        $userIds = array_filter(array_unique($userIds));
        $data = new \haibao\jiepai\data\User();

        $userInfoList = $data->getUsersByIds($userIds);
        foreach ($userInfoList as $userInfo) {
            $userNickNames[$userInfo['UserID']] = $userInfo['NickName'];
        }
        return $userNickNames;
    }

    /**
     * 获取用户收藏的文章
     */
    public static function getUserActionsListByType($articleType, $userId, $cursor = null)
    {

        $data = new UserData();
        $actionList = $data->getUserActionsListByType($articleType, $userId, $cursor);

        $finalList = array();
        $actionMap = array();
        if ($actionList) {
            foreach ($actionList as $key => $action) {
                $actionMap[$action['TypeID']] = $action['ID'];
            }
            switch ($articleType) {
                case \haibao\jiepai\model\data\user\CmsUserAction::TYPE_ARTICLE_MARK:
                    $data = new \haibao\jiepai\data\Article();
                    $finalList = $data->getArticleInfoById(array_map("array_shift", $actionList));
            }
        }
        if ($finalList) {
            foreach ($finalList as $key => $find) {
                $finalList[$key]['ID'] = isset($actionMap[$find['ArticleID']]) ? $actionMap[$find['ArticleID']] : null;
            }
        }

        return $finalList;
    }

    /**
     * 取消收藏图片
     */
    public static function cancelCollectPictureToAlbum($userId, array $contentIdList, $albumId = null)
    {
        $contentIdList = array_unique(array_filter($contentIdList));
        if (!$userId || !$contentIdList) {
            return false;
        }
        $data = new UserData();
        $count = $data->cancelCollectPictureToAlbum($userId, $contentIdList, $albumId);

        return intval($count);
    }

    /**
     * 收藏图片到相册
     */
    public static function CollectPictureToAlbum($userId, array $contentIds, $albumId)
    {
        $pictureIdList = array_unique(array_filter($contentIds));
        if (!$userId || !$pictureIdList || !$albumId) {
            return false;
        }
        $data = new UserData();
        $data->CollectPictureToAlbum($userId, $contentIds, $albumId);

        return $data->getAlbumPictureNum($albumId, $userId);
    }

    /**
     * 剪裁用户头像
     */
    private static function imagecropper($source_path, $dest_path, $target_width, $target_height)
    {
        $source_info = @getimagesize($source_path);
        $source_width = $source_info[0];
        $source_height = $source_info[1];
        $source_mime = $source_info['mime'];
        $source_ratio = $source_height / $source_width;
        $target_ratio = $target_height / $target_width;

        if ($source_ratio > $target_ratio) {
            $cropped_width = $source_width;
            $cropped_height = $source_width * $target_ratio;
            $source_x = 0;
            $source_y = ($source_height - $cropped_height) / 2;
        } elseif ($source_ratio < $target_ratio) {
            $cropped_width = $source_height / $target_ratio;
            $cropped_height = $source_height;
            $source_x = ($source_width - $cropped_width) / 2;
            $source_y = 0;
        } else {
            $cropped_width = $source_width;
            $cropped_height = $source_height;
            $source_x = 0;
            $source_y = 0;
        }

        switch ($source_mime) {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;
            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;
            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;
            default:
                return false;
                break;
        }

        $target_image = imagecreatetruecolor($target_width, $target_height);
        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);

        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);

        switch ($source_mime) {
            case 'image/gif':
                imagegif($target_image, $dest_path);
                break;
            case 'image/jpeg':
                imagejpeg($target_image, $dest_path);
                break;
            case 'image/png':
                imagepng($target_image, $dest_path);
                break;
        }
        imagedestroy($source_image);
        imagedestroy($target_image);
        imagedestroy($cropped_image);
    }

    /**
     * @param \haibao\user\model\data\UserLogin $userLoginModel
     * 用手机号码注册
     */
    public static function saveUserByMobile($userLoginModel)
    {
        $userLoginModel->LoginNameType = \haibao\user\model\data\UserLogin::LOGIN_NAME_TYPE_MOBILE;
        $userLoginModel->SysAppType = \haibao\user\model\data\UserLogin::SYS_APP_TYPE_APP;
        $userLoginModel->OpenAppType = \haibao\user\model\data\UserLogin::OPEN_APP_TYPE_USER;
        $userLoginModel->Password = self::encrypt($userLoginModel->Password);
        $userLoginModel->CreateTime = new \DateTime();

        // 保存用户注册信息
        $userData = new \haibao\user\data\User();
        return $userData->saveUser($userLoginModel);
    }

    /**
     * @param \haibao\user\model\data\UserLogin $userLoginModel
     * 保存第三方用户登录信息
     */
    public static function saveThirdUserInfo($userLoginModel)
    {
        $userData = new \haibao\user\data\User();
        $nickName = self::filterUtf8Char(trim($userLoginModel->NickName));

        $nickName = $userData->getUserIdByNickName($nickName) ? self::randNickname($nickName) : $nickName;
        $userLoginModel->NickName = $nickName;
        $userLoginModel->Password = self::encrypt(rand(pow(10, 5), pow(10, 6) - 1));

        $userData->saveUser($userLoginModel, $userLoginModel->LoginName);
    }

    /**
     * 昵称后加4为随机数
     */
    public static function randNickname($nickname){
        $nickname .= rand(1000, 9999);
        $userData = new \haibao\user\data\User();
        if(!$userData->getUserIdByNickName($nickname)){
            return $nickname;
        }else{
            self::randNickname($nickname);
        }
    }

    /**
     * 检查用户密码是否正确
     */
    public static function checkPasswordByUserId($userId, $password)
    {
        $data = new \haibao\user\data\User();
        $dbPassword = $data->getPasswordByUserId($userId);
        return \haibao\user\business\User::checkPassword($password, $dbPassword);
    }

    /**
     * 修改用户登录后的设备相关信息
     */
    public static function updateLoginInfo($userId, $DeviceID, $DeviceName, $sid)
    {
        $userModel = new \haibao\jiepai\model\data\user\CmsUsers();
        $userModel->Id = $userId;
        $userModel->LastLoginDevice = $DeviceID;
        $userModel->DeviceName = $DeviceName;
        $userModel->Sid = $sid;

        $filter = new \haibao\jiepai\model\filter\user\CmsUsers();
        $filter->where($filter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_EQUAL, $userId);
        $userInfo = \haibao\jiepai\business\User::getOneByFilter($filter);
        if ($userInfo) {
            $userModel->LastLoginSid = $userInfo->Sid;
        }
        self::updateCmsUser($userModel);
        self::replaceVisitorToUser($DeviceID, $userId);
        return $userInfo;
    }

    /**
     * 保存用户信息到街拍的用户表中
     */
    public static function saveCmsUser($userModel)
    {
        $userModel->Message = '你已于' . date('Y-m-d H:i') . '在其他设备(' . $userModel->DeviceName . ')上进行登录';
        $userModel->CreateTime = new \DateTime();

        $data = new \haibao\jiepai\data\User();
        $data->saveCmsUser($userModel);

        // 创建默认相册
        \haibao\jiepai\business\Album::createDefaultAlbum($userModel->Id);
        // 首次进入消息提示
        \haibao\jiepai\business\Message::firstEntryMessage($userModel->Id);
    }

    /**
     * 根据OpenId查询第三方用户信息
     */
    public static function getUserByOpenId($openId, $loginNameType, $openAppType)
    {
        $userData = new \haibao\user\data\User();
        return $userData->getUserIdByOpenId($openId, $loginNameType, $openAppType);
    }

    /**
     * 修改用户信息
     */
    public static function updateCmsUser($userModel)
    {
        $userModel->Message = '你已于' . date('Y-m-d H:i') . '在其他设备(' . $userModel->DeviceName . ')上进行登录';

        $data = new UserData();
        $data->updateUser($userModel->Id, array(
            'Sid' => $userModel->Sid,
            'LastLoginDevice' => $userModel->LastLoginDevice,
            'LastLoginSid' => $userModel->LastLoginSid,
            'Message' => $userModel->Message
        ));
    }

    /**
     * 发送注册短信验证码
     */
    public static function sendCode($mobile, $type)
    {
        $code = rand(pow(10, 5), pow(10, 6) - 1);
        $cache = new \haibao\user\cache\User();
        $cache->setSmsCaptcha($mobile, $code, 60 * 10);
        if ($type == 1) {
            $templateId = \haibao\sms\SMS::TEMPLATE_2005;
        } elseif ($type == 2) {
            $templateId = \haibao\sms\SMS::TEMPLATE_2006;
        }
        \haibao\sms\SMS::sendSms($mobile, $templateId, array(
            $code
        ));
    }

    /**
     * 检验验证码是否正确
     */
    public static function getSmsCode($mobile)
    {
        $cache = new \haibao\user\cache\User();
        return $cache->getSmsCaptcha($mobile);
    }

    /**
     * 修改用户昵称，包括街拍库和用户库中的昵称
     */
    public static function updateUserNickName($userId, $nickname)
    {
        $userModel = new \haibao\user\model\data\UserReg();
        $userModel->NickName = $nickname;
        $userModel->Gender = \haibao\user\model\data\UserReg::Gender_TYPE_GIRL;

        $userData = new \haibao\user\data\User();
        $userData->setUserInfo($userId, $userModel);

        $data = new UserData();
        $data->updateUser($userId, array('NickName' => $nickname));
    }

    /**
     * 用户密码加密
     */
    public static function encrypt($password)
    {
        $str = rand(0, 1);
        $pwd_prefix = sha1($str);
        $pwd_prefix = substr($pwd_prefix, 0, 5);
        $pwd = sha1($pwd_prefix . $password);
        $pwd = 'sha1$' . $pwd_prefix . '$' . $pwd;;
        return $pwd;
    }

    /**
     * 过滤字符串,保留UTF8字母数字中文及部份符号
     */
    private static function filterUtf8Char($ostr)
    {
        preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $ostr, $matches);
        $str = join('', $matches[0]);
        if ($str == '') { // 含有特殊字符需要逐個處理
            $returnstr = '';
            $i = 0;
            $str_length = strlen($ostr);
            while ($i <= $str_length) {
                $temp_str = substr($ostr, $i, 1);
                $ascnum = Ord($temp_str);
                if ($ascnum >= 224) {
                    $returnstr = $returnstr . substr($ostr, $i, 3);
                    $i = $i + 3;
                } elseif ($ascnum >= 192) {
                    $returnstr = $returnstr . substr($ostr, $i, 2);
                    $i = $i + 2;
                } elseif ($ascnum >= 65 && $ascnum <= 90) {
                    $returnstr = $returnstr . substr($ostr, $i, 1);
                    $i = $i + 1;
                } elseif ($ascnum >= 128 && $ascnum <= 191) { // 特殊字符
                    $i = $i + 1;
                } else {
                    $returnstr = $returnstr . substr($ostr, $i, 1);
                    $i = $i + 1;
                }
            }
            $str = $returnstr;
            preg_match_all('/[\x{FF00}-\x{FFEF}|\x{0000}-\x{00ff}|\x{4e00}-\x{9fff}]+/u', $str, $matches);
            $str = join('', $matches[0]);
        }
        return $str;
    }

}